import { h } from 'vue'
import dayjs from 'dayjs'

export const openCloseAll = (text, type = 'warning') => {
  ElMessage.closeAll()
}

export const openMessage = (text, type = 'warning') => {
  ElMessage({
    message: text,
    type,
    dangerouslyUseHTMLString: true
  })
}

export const reconfirmMessage = (text, type = 'warning') => {
  return ElMessageBox.confirm(text, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type
  })
}

// 对象的深拷贝
export const deepCopy = (obj) => {
  return JSON.parse(JSON.stringify(obj))
}

export const deepClone = (obj) => {
  if (typeof obj !== 'object') return
  let newObj = obj instanceof Array ? [] : {}
  for (let key in obj) {
    if (typeof obj[key] === 'object') {
      newObj[key] = deepClone(obj[key])
    } else {
      newObj[key] = obj[key]
    }
  }
  return newObj
}
// 事件防抖
export const debounce = function (callback, time) {
  let timer = null
  return function () {
    if (timer) clearInterval(timer)
    let self = this
    timer = setTimeout(function () {
      callback.call(self, ...arguments)
    }, time)
  }
}
// 事件节流
export const _throttle = function (fn, wait = 200) {
  let last, timer, now
  return function () {
    now = Date.now()
    if (last && now - last < wait) {
      clearTimeout(timer)
      timer = setTimeout(function () {
        last = now
        fn.call(this, ...arguments)
      }, wait)
    } else {
      last = now
      fn.call(this, ...arguments)
    }
  }
}
// 类型判断
export const getType = (data) => {
  return Object.prototype.toString.call(data).slice(8, -1)
}

// 获取url参数 xxx?yy=zz => {xx:zz} || paramsKey => value
export const getUrlParam = (url, paramsKey) => {
  var result = {}
  if (url.indexOf('?') == -1) return null
  let urlArr = url.split('?')[1].split('&')
  urlArr.forEach((ele) => {
    let arr = ele.split('=')
    result[arr[0]] = arr[1]
  })
  if (paramsKey) return result[paramsKey] || ''
  else return result
}

// 设备信息
export const getEquipmentInfo = () => {
  let userAgent = navigator.userAgent
  const k = ['Android', 'iPhone', 'iPad', 'Mac', 'Windows', 'Linux']
  const data = {
    equipement: k.find((ele) => userAgent.indexOf(ele) !== -1),
    clientWidth: document.body.clientWidth
  }
  return data
}

export const calculater = (date) => {
  const year = date.split('-')[0]
  const month = date.split('-')[1]
  const day = date.split('-')[2]
  const birthDayTime = new Date(date).getTime()
  const nowTime = new Date().getTime()
  const zodiac = {
    0: '猴',
    1: '鸡',
    2: '狗',
    3: '猪',
    4: '鼠',
    5: '牛',
    6: '虎',
    7: '兔',
    8: '龙',
    9: '蛇',
    10: '马',
    11: '羊'
  }

  const constellation = '魔羯水瓶双鱼牡羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯'.substr(
    month * 2 - (day < '102223444433'.charAt(month - 1) - -19) * 2,
    2
  )
  return {
    constellation,
    zodiac: zodiac[year % 12] || '',
    age:
      Math.floor((nowTime - birthDayTime) / 31536000000) > 0
        ? Math.floor((nowTime - birthDayTime) / 31536000000)
        : 1
  }
}

/**
 *
 * @param {*} records - 数组数据
 * @param {*} oldId - 上级id
 * @returns - 返回树形菜单chidren
 */
const getChilds = (records, oldId) => {
  let childs = []
  records.forEach((val) => {
    oldId === val.parentId && childs.push({ ...val })
  })
  childs.forEach((childNode) => {
    let currNode = getChilds(records, childNode.oldId)
    currNode.length > 0 && (childNode.children = currNode)
  })
  return childs
}
/**
 *顶层节点依据: 传入的rootId为顶层节点，数据的parentId为rootId的时候，说明该条数据是顶层节点的下一层
 * @param {Array} records - 数组数据
 * @param {string} rootId - 根节点id
 * @returns {Array} 返回结果数据
 */
export const formTreeByParentId = (records, rootId) => {
  var result = []
  records.forEach((val) => {
    if (val.parentId === rootId) {
      let parent = { ...val }
      parent.children = getChilds(records, val.oldId)
      result.push(parent)
    }
  })
  return result
}

/**
 * 时间戳转年月日
 * @param {string} date - 需要修改的时间
 * @param {string} format - 格式
 * @param {string} delimiter - 分隔线
 * @returns {string} 返回结果数据
 */
export const dateConvert = (date, format, delimiter) => {
  let str1 = format ? format : ['M', 'D', 'Y']
  let str2 = delimiter ? delimiter : '/'
  let newDate = new Date(date)
  let Y = newDate.getFullYear()
  let M = newDate.getMonth() + 1 < 10 ? '0' + (newDate.getMonth() + 1) : newDate.getMonth() + 1
  let D = newDate.getDate() < 10 ? '0' + newDate.getDate() : newDate.getDate()
  let value = ''
  str1.forEach((item, i) => {
    if (item == 'Y') {
      value += Y
    }
    if (item == 'M') {
      value += M
    }
    if (item == 'D') {
      value += D
    }
    if (i < 2) {
      value += str2
    }
  })
  return value
}

export const dateDiff = (sDate1, sDate2) => {
  let aDate, oDate1, oDate2, iDays
  aDate = sDate1.split('-')
  oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]) //转换为12-18-2006格式
  aDate = sDate2.split('-')
  oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0])
  iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24) //把相差的毫秒数转换为天数
  return iDays
}

export const submitAllForm = (refList) => {
  let list = []
  refList.forEach((ele) => {
    list.push(checkForm(ele))
  })
  return Promise.all(list)
}

const checkForm = (formName) => {
  return new Promise((resolve, reject) => {
    formName.value.validate((valid) => {
      if (valid) {
        resolve()
      } else {
        reject()
        return false
      }
    })
  })
}

// 输入-数字/负数/小数
export const inputNumber = (val, type, num) => {
  // type: 1-负数  2-小数  3-(0-100)  4-小于100的两位小数 6 小于一百且小数位为num
  // num type为小数时，小数点后几位
  let str = String(val)
  if (type == 1) {
    let first = str.charAt(0)
    // str = str.replace(/[^\d]/g, "");
    // 先把非数字的都替换掉，除了数字和.
    str = str.replace(/[^\d\.]/g, '')
    // 必须保证第一个为数字而不是.
    str = str.replace(/^\./g, '')
    // 保证只有出现一个.而没有多个.
    str = str.replace(/\.{2,}/g, '.')
    // 保证.只出现一次，而不能出现两次以上
    str = str.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
    str = str.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, '$1')
    if (first === '-') {
      str = '-' + str
    }
  } else if (type == 2) {
    // 先把非数字的都替换掉，除了数字和.
    str = str.replace(/[^\d\.]/g, '')
    // 必须保证第一个为数字而不是.
    str = str.replace(/^\./g, '')
    // 保证只有出现一个.而没有多个.
    str = str.replace(/\.{2,}/g, '.')
    // 保证.只出现一次，而不能出现两次以上
    str = str.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
    if (num) {
      if (num == 3) {
        str = str.replace(/^\D*([0-9]\d*\.?\d{0,3})?.*$/, '$1')
      } else if (num == 4) {
        str = str.replace(/^\D*([0-9]\d*\.?\d{0,4})?.*$/, '$1')
      }
    } else {
      str = str.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, '$1')
    }
  } else if (type == 3) {
    if (/^([0-9]{1,2}|100)$/.test(str)) {
      str = str
    } else {
      str = ''
    }
  } else if (type == 4) {
    str = str.replace(/[^\d\.]/g, '')
    str = str.replace(/^\./g, '')
    str = str.replace(/\.{2,}/g, '.')
    str = str.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
    str = str.replace(/^\D*([0-9]\d*\.?\d{0,3})?.*$/, '$1')
    if (Number(str) <= 100) {
      str = str
    } else {
      str = ''
    }
  } else if (type == 5) {
  } else if (type == 6) {
    str = str.replace(/[^\d\.]/g, '')
    // 必须保证第一个为数字而不是.
    str = str.replace(/^\./g, '')
    // 保证只有出现一个.而没有多个.
    str = str.replace(/\.{2,}/g, '.')
    // 保证.只出现一次，而不能出现两次以上
    str = str.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
    if (num) {
      if (num == 3) {
        str = str.replace(/^\D*([0-9]\d*\.?\d{0,3})?.*$/, '$1')
      } else if (num == 4) {
        str = str.replace(/^\D*([0-9]\d*\.?\d{0,4})?.*$/, '$1')
      } else if (num == 2) {
        str = str.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, '$1')
      } else if (num == 1) {
        str = str.replace(/^\D*([0-9]\d*\.?\d{0,1})?.*$/, '$1')
      }
      if (Number(str) <= 100) {
        str = str
      } else {
        str = ''
      }
    } else {
      str = str.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, '$1')
    }
  } else {
    str = str.replace(/[^\d]/g, '')
  }
  return str
}

// 验证数字长度
export const numLengthVerify = (val, num) => {
  if (val) {
    val = val + ''
    if (val.length > num) {
      val = val.substring(0, num)
    } else if (val.length < num) {
      val = ''
      openCloseAll()
      openMessage('The input length is limited to ' + num + ' digits')
    }
  } else {
    val = ''
  }
  return val
}

// 计算佣金  type-类型 arr-数组 val-值 strIndex-判断字段 maxNum-最大值 itemIndex-数组下标
export const calculateRatio = (type, arr, val, strIndex, maxNum, itemIndex) => {
  let str = val
  if (str) {
    let mes = ''
    if (type == 1) {
      mes = 'Total team split must less than 100%'
    } else if (type == 2) {
      mes = 'Total team split must less than 100%'
    }
    // 先把非数字的都替换掉，除了数字和.
    str = str.replace(/[^\d\.]/g, '')
    // 必须保证第一个为数字而不是.
    str = str.replace(/^\./g, '')
    // 保证只有出现一个.而没有多个.
    str = str.replace(/\.{2,}/g, '.')
    // 保证.只出现一次，而不能出现两次以上
    str = str.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
    if (type == 1) {
      str = str.replace(/^\D*([0-9]\d*\.?\d{0,3})?.*$/, '$1')
    } else if (type == 2) {
      str = str.replace(/^\D*([0-9]\d*\.?\d{0,1})?.*$/, '$1')
    }
    if (arr.length > 0) {
      let num = 0
      arr.forEach((item, index) => {
        if (itemIndex || itemIndex === 0) {
          if (index != itemIndex) {
            num += Number(item[strIndex])
          }
        } else {
          num += Number(item[strIndex])
        }
      })
      if (Number(str) + num > maxNum) {
        str = ''
        openCloseAll()
        openMessage(mes)
      }
    } else {
      if (Number(str) > maxNum) {
        str = ''
        openMessage(mes)
      }
    }
  }
  return str
}

// 邮箱
export const emailVerify = (val) => {
  let str = val
  if (str) {
    // let req = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/;
    let req =
      /^[-A-Za-z0-9~!$%^&*_=+}{\'?]+(\.[-A-Za-z0-9~!$%^&*_=+}{\'?]+)*@([A-Za-z0-9_][-A-Za-z0-9_]*(\.[-A-Za-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|AERO|ARPA|BIZ|COM|COOP|EDU|GOV|INFO|INT|MIL|MUSEUM|NAME|NET|ORG|PRO|TRAVEL|MOBI[A-Za-z][A-Za-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/
    if (req.test(str)) {
      str = str
    } else {
      str = ''
    }
  }
  return str
}

// @blur="data.listingFormData.phone=phoneVerify(data.listingFormData.phone)"
// @blur="data.listingFormData.email=emailVerify(data.listingFormData.email)"
// 手机号
export const phoneVerify = (params) => {
  params = typeof params == 'number' ? `${params}` : params.replace(/ /g, '')
  const str = params.split('').filter((ele) => ele && !isNaN(Number(ele)))
  return str.length < 10
    ? ''
    : `(${str[0]}${str[1]}${str[2]}) ${str[3]}${str[4]}${str[5]}-${str[6]}${str[7]}${str[8]}${str[9]}`
}

// 保留几位小数，整数不保留小数
export const retainDecimal = (val, num) => {
  let str = num ? num : 3
  if (val) {
    val = val + ''
    val = parseFloat(parseFloat(val).toFixed(str))
    val = val.toString()
  } else {
    val = ''
  }
  return val
}

// 金额-替换
export const moneyReplace = (num, max = -1) => {
  if (max !== -1 && num > max) {
    return ''
  }
  if (num >= 1) {
    num = num + ''
    num = num.replace(/\,/g, '')
    // num = parseFloat(num);
    num = parseFloat(parseFloat(num).toFixed(2))
    num = num.toLocaleString()
    let len = 0
    let newValue = num.toString()
    num = newValue
  } else if (num === 0) {
    num = 0
  } else if (num === '0') {
    num = '0'
  } else if (num > 0) {
    num = String(num).replace(/^(.*\..{4}).*$/, '$1')
    return num
  } else if (num < 0) {
    num = String(num).replace(/^(.*\..{4}).*$/, '$1')
    return num
  } else {
    num = ''
  }
  return num
}

export const randomId = (list) => {
  let id = Math.random()
  let index = list.findIndex((ele) => ele.id == id)
  if (index == -1) return id
  else return randomId(list)
}

export const copyText = (text) => {
  var textareaC = document.createElement('textarea')
  textareaC.setAttribute('readonly', 'readonly') //设置只读属性防止手机上弹出软键盘
  textareaC.value = text
  document.body.appendChild(textareaC) //将textarea添加为body子元素
  textareaC.select()
  var res = document.execCommand('copy')
  document.body.removeChild(textareaC) //移除DOM元素
  openMessage('copy success', 'success')
}

export const getItemByIdInTree = (id, tree) => {
  let res = null
  for (let i = 0; i < tree.length; i++) {
    let ele = tree[i]
    ele.id == id ? (res = ele) : ''
    if (res) break
    if (ele.list.length) {
      res = getItemByIdInTree(id, ele.list)
    }
  }
  return res
}

let colorArr = []

export const rdmRgbColor = (type = 1) => {
  //随机生成RGB颜色
  const arr = []
  for (let i = 0; i < 3; i++) {
    if (type) {
      // 暖色
      arr.push(Math.floor(Math.random() * 128 + 64))
    } else {
      // 亮色
      arr.push(Math.floor(Math.random() * 128 + 128))
    }
  }
  const [r, g, b] = arr
  // rgb颜色
  // var color=`rgb(${r},${g},${b})`;
  // 16进制颜色
  const color = `#${
    r.toString(16).length > 1 ? r.toString(16) : '0' + r.toString(16)
  }${g.toString(16).length > 1 ? g.toString(16) : '0' + g.toString(16)}${
    b.toString(16).length > 1 ? b.toString(16) : '0' + b.toString(16)
  }`
  if (colorArr.find((ele) => ele == color)) {
    return rdmRgbColor()
  } else {
    colorArr.push(color)
    return color
  }
}

export const parseColor = (color) => {
  if (!color) return ''
  return (
    'rgb(' +
    parseInt('0x' + color.slice(1, 3)) +
    ',' +
    parseInt('0x' + color.slice(3, 5)) +
    ',' +
    parseInt('0x' + color.slice(5, 7)) +
    ',1)'
  )
}

export const matchPhoneNumber = (params) => {
  params = typeof params == 'number' ? `${params}` : params.replace(/ /g, '')
  const str = params.split('').filter((ele) => ele && !isNaN(Number(ele)))
  return str.length < 10
    ? ''
    : `(${str[0]}${str[1]}${str[2]}) ${str[3]}${str[4]}${str[5]}-${str[6]}${str[7]}${str[8]}${str[9]}`
}

export const getDateYearLater = (params) => {
  return dayjs(params).add('1', 'year').format('MM/DD/YYYY')
}

// 两个日期-月份差
export const reduMonths = (startVal, endVal) => {
  if (startVal && endVal) {
    let minDate = new Date(startVal)
    let minYear = minDate.getFullYear()
    let minMonth = minDate.getMonth() + 1
    let maxDate = new Date(endVal)
    let maxYear = maxDate.getFullYear()
    let maxMonth = maxDate.getMonth() + 1
    return maxYear * 12 + maxMonth - (minYear * 12 + minMonth) + 1
  } else {
    return 0
  }
}

/**
 * templateRevis  canvas 模板替换文字 图片
 * @param {string} photo - 模板图片（需要处理的图片）
 * @param {Array} gathers - 替换集合 列表中的值仅包含下面两种类型 且每种类型的属性全部必填
 *      {
 *        text:'',x:0,y:'',type:'text'
 *      }
 *      {
 *        img:'',x:0,y:0,width:0,height:0,type:'img'
 *      }
 * @param {Object} configs - 配置模板大小 图片大小 值为width 和 height 非必填
 * @resolve {string} promise返回结果为处理后的图片url
 **/

export const templateRevise = (photo, gathers, configs = {}) => {
  const config = Object.assign(configs, {
    width: 500,
    height: 500
  })

  let canvas = document.createElement('canvas')
  canvas.width = config.width
  canvas.height = config.height
  canvas.style.backgroundColor = '#ffffff'
  let ctx = canvas.getContext('2d')

  return new Promise((resolve, reject) => {
    const template = new Image()
    template.src = photo

    let status = 1

    template.onload = function () {
      ctx.drawImage(template, 0, 0, config.width, config.height)
      gathers.forEach((ele) => {
        switch (ele.type) {
          case 'text':
            ctx.font = ele.font || '22px small-caps'
            ctx.fillStyle = ele.fillStyle || '#000000'
            ctx.fillText(ele.text, ele.x, ele.y)
            break
          case 'img':
            const img = new Image()
            img.src = ele.img
            status = 0
            img.onload = function () {
              ctx.drawImage(img, ele.x, ele.y, ele.width, ele.height)
              status = 1
            }
            break
          default:
            break
        }
      })
      let interval = null
      interval = setInterval(() => {
        if (status) {
          resolve(canvas.toDataURL())
          clearInterval(interval)
        }
      }, 500)
    }
  })
}

// contextChange 转换 </#if> 和 <*#if>
export const contextChange = (content) => {
  if (content.includes('&lt;/#if&gt;')) {
    return content.replaceAll('&lt;/#if&gt;', '&lt;*#if&gt;')
  } else if (content.includes('&lt;*#if&gt;')) {
    return content.replaceAll('&lt;*#if&gt;', '&lt;/#if&gt;')
  }
  return content
}

export function clearAllCookie() {
  var keys = document.cookie.match(/[^ =;]+(?=\=)/g)
  if (keys) {
    for (var i = keys.length; i--; )
      document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString()
  }
}
